package it.cums.util;

import it.cums.model.Order;
import it.cums.model.OrderedProduct;
import it.cums.model.OrderedProducts;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class OrderedProductManager {
	private static OrderedProductManager orderedProductManager;
	
	private OrderedProductManager() {
	}
	
	public static OrderedProductManager getInstance() {
		if (orderedProductManager == null) {
			orderedProductManager = new OrderedProductManager();
		}
		return orderedProductManager;
	}
	
	public void storeOrderedProducts(Session session, OrderedProducts products, Order order) throws Exception {
		deleteOrderedProducts(session, order);
		insertOrderedProducts(session, products);
	}
		
	@SuppressWarnings("unchecked")
	public List<OrderedProduct> listOrderedProducts(Order order) {
		Session session = null;
		Transaction tx = null;
		List<OrderedProduct> products = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
		    tx = session.beginTransaction();
		    Query query = session.createQuery("from OrderedProduct as p where p.order.id = :id order by p.id");
		    query.setInteger("id", order.getId());
		    products = query.list();
		    tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			HibernateUtil.rollback(tx);
		} finally {
			HibernateUtil.closeSession(session);
		}
		return products;
    }
	
	public void deleteOrderedProducts(Session session, Order order) throws Exception {
		Query query = session.createQuery("delete OrderedProduct p where p.order.id = :id");
		query.setInteger("id", order.getId());
		query.executeUpdate();
	}
	
	private void insertOrderedProducts(Session session, OrderedProducts products) throws Exception {
		for (OrderedProduct product : products.getOrderedProducts()) {
			session.save(product);
		}
	}
}